// include styles
import "~/rodal/lib/rodal.css";
import * as React from "react";
import { List, Checkbox, Button } from "antd-mobile";
import "./index.scss";
import Rodal from "rodal";
import formcontext from "../form";

const { CheckboxItem } = Checkbox;
export default props => {
  const [ visible, changevisible ] = React.useState(false);
  const show = () => {
    changevisible(true);
  };

  const hide = (e) => {
    e.stopPropagation();
    changevisible(false);
  };

  const { node } = props;
  const { datasource } = node.data;
  const labelText = node.data.label;
  const form = React.useContext(formcontext);
  const { getFieldDecorator, getFieldValue } = form;
  const value = getFieldValue(node.data.column);
  return (
    <div
      className="formitem" {...props.data}
      onClick={() => show()}
    >
      <label>{labelText || "选择"}</label>
      <label>
        {value ? (typeof value === "string" ? value : value.join("、")) : null}
      </label>
      <Rodal
        onClose={(e) => hide(e)}
        customStyles={{
          width: "50vw",
          height: "60vh",
        }}
        visible={visible}
      >
        {getFieldDecorator(node.data.column)(<Checkboxgroup options={datasource.value} />)}
        <Button
          style={{
            position: "absolute",
            margin: "auto",
            bottom: "3vh",
            left: "3vw",
            right: "3vw",
            padding: "0 10vw",
          }}
          onClick={(e) => hide(e)}
          type="primary"
        >
          确认
        </Button>
      </Rodal>
    </div>
  );
};

class Checkboxgroup extends React.Component {
  static defaultProps = {
    value: [],
  };

  render() {
    const { options, onChange, value, disabled } = this.props;
    return (
      <List>
        {options.map((option) => (
          <CheckboxItem
            key={option}
            checked={value ? typeof value === "string" ? value.split("、") : value.find((i) => i === option) : false}
            onChange={() => {
              if (disabled) {
                return;
              }
              const index = value.findIndex((element) => element === option);
              if (index > -1) {
                const tempval = [...value];
                tempval.splice(index, 1);
                onChange(tempval);
              } else {
                onChange([ ...value, option ]);
              }
            }}
          >
            {option}
          </CheckboxItem>
        ))}
      </List>
    );
  }
}
